package com.ht.api.hlink;

import javax.sql.DataSource;

import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.hlink.function.HlinkFunction;
import com.ht.api.open.OpenUtil;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 计算朋友圈分区值
 * @author asq
 * @createTime 2025年3月24日 11:16:50
 */
@Slf4j
public class GetMomentPartition implements HlinkFunction<Integer> {
	/** 发朋友圈时，同一客服下面最多能发给5000个粉丝 */
	private static final int MAX = 5000;
	/** 标签组名称 */
	private static final String TAG_GROUP_NAME = "朋友圈分区";
	/** 接口ID：添加企业客户标签 */
	private static final long API_ID_ADD = 1896076213701709824L;
	/** 接口ID：打标签 */
	private static final long API_ID_TAG = 1896150837936394240L;

	@Override
	public Integer format(DataSource ds, Object value, Entity entity) {
		// 非新增时直接返回
		Integer isnew = entity.getInt("isnew");
		if (isnew == null || isnew != 1) {
			return entity.getInt("moment_partition");
		}
		// 企微初始化时不需要计算，直接返回null
		Integer isinit = entity.getInt("isinit");
		if (isinit != null && isinit == 1) {
			return null;
		}
		
		// 获取客服ID
		String userid = entity.getStr("userid");

		// 计算此客服下的最新分区值
		Integer curPartition = Db.createSqlParser("wx_moment_tag").where("userid", userid)
				.select("max(moment_partition)").val(ds, Integer.class);
		int partition = curPartition != null ? curPartition : 0;
		long curCustomerCount = Db.createSqlParser("wx_workuser_customer").where("userid", userid).where("type", 1)
				.count(ds);
		int newPartition = partition;
		Entity wxMomentTag = null;
		if (curCustomerCount >= (MAX * partition)) {
			newPartition = ++partition;

			// 查询客服
			Entity wxWorkuser = Db.createSqlParser("wx_workuser").where("userid", userid).findOne(ds);
			String tagName = String.format("%s_%s", wxWorkuser.getMainId(), newPartition);

			// 创建朋友圈标签表数据
			String appid = wxWorkuser.getStr("tenant_appid");
			wxMomentTag = Db.createEntity("wx_moment_tag");
			wxMomentTag.set("appid", appid);
			wxMomentTag.set("userid", userid);
			wxMomentTag.set("moment_partition", newPartition);
			wxMomentTag.set("tag_name", tagName);
			wxMomentTag.set("status", 0);
			Db.insert(ds, wxMomentTag);
			
			// 调用企微接口创建标签以及打标
			createTag(ds, entity, wxMomentTag);
		} else {
			// 找到已存在的分区标签，后面需要打标签
			wxMomentTag = Db.createSqlParser("wx_moment_tag").where("userid", userid)
					.where("moment_partition", partition).findOne(ds);
		}
		
		// 调用企微接口打标签
		doTag(ds, entity, wxMomentTag);
		
		return newPartition;
	}

	/**
	 * 调用企微接口创建标签
	 * @param ds 数据源
	 * @param wxWorkuserCustomer 企微客户
	 * @param wxMomentTag 朋友圈分区标签
	 */
	private void createTag(DataSource ds, Entity wxWorkuserCustomer, Entity wxMomentTag) {
		String tagName = wxMomentTag.getStr("tag_name");
		String appid = wxMomentTag.getStr("appid");
		
		// 调用接口创建标签
		JSONObject param = JSONUtil.createObj();
		param.set("group_name", TAG_GROUP_NAME);
		param.set("order", 0);
		param.set("tag", JSONUtil.createObj().set("name", tagName));
		log.info("[CreateMomentTag]开始创建企微标签，tagName:{}", tagName);
		String str = OpenUtil.callByNoAssemble(appid, API_ID_ADD, param);

		// 如果企微接口调用成功，则立即标记此标签已创建
		JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") == 0) {
			JSONArray wxTagArr = obj.getByPath("tag_group.tag", JSONArray.class);
			JSONObject wxTag = wxTagArr.getJSONObject(0);
			String tagId = wxTag.getStr("id");
			
			wxMomentTag.set("tag_id", tagId);
			wxMomentTag.set("status", 1);
			Db.insert(ds, wxMomentTag);
			log.info("[CreateMomentTag]创建标签成功，tagName:{}", tagName);
		}
	}
	
	/**
	 * 调用企微接口打标签
	 * @param ds 数据源
	 * @param wxWorkuserCustomer 企微客户
	 * @param wxMomentTag 朋友圈分区标签
	 */
	private void doTag(DataSource ds, Entity wxWorkuserCustomer, Entity wxMomentTag) {
		String tagName = wxMomentTag.getStr("tag_name");
		String appid = wxMomentTag.getStr("appid");
		
		// 调用企微接口打标签
		log.info("[CreateMomentTag]开始打标，tagName:{}", tagName);
		JSONArray addTagArr = JSONUtil.createArray();
		addTagArr.add(wxMomentTag.getStr("tag_id"));
		JSONObject param = JSONUtil.createObj()
				.set("userid", wxMomentTag.getStr("userid"))
				.set("external_userid", wxWorkuserCustomer.getStr("external_userid"))
				.set("add_tag", addTagArr);
		
		// 调用企微接口打标
		String str = OpenUtil.call(appid, API_ID_TAG, param);
		
		// 如果企微接口调用成功，则立即标记此标签已创建
		JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") == 0) {
			log.info("[CreateMomentTag]打标完成，tagName:{}", tagName);
			wxMomentTag.set("status", 2);
			Db.insert(ds, wxMomentTag);
		}
	}

}
